package com.base.cn.platform.os.controller.op.activity;

import com.base.cn.platform.os.common.controller.BaseController;
import com.base.cn.platform.os.common.mybatis.Pagination;
import com.base.cn.platform.os.common.utils.DataUtil;
import com.base.cn.platform.os.common.utils.ObjectUtils;
import com.base.cn.platform.os.common.utils.StringUtils;
import com.base.cn.platform.os.common.utils.result.ResultUtil;
import com.base.cn.platform.os.entity.op.ActivityCodeCondition;
import com.base.cn.platform.os.entity.op.activity.OpActivity;
import com.base.cn.platform.os.entity.op.coupon.OpCouponCode;
import com.base.cn.platform.os.service.op.activity.OpActivityBiz;
import com.base.cn.platform.os.service.op.coupon.OpCouponCodeBiz;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

/**
 * 促销活动ontroller
 *
 * @author ll
 * @create 2018-05-09
 */
@RestController
@RequestMapping("/manage/op")
public class OpActivityController extends BaseController {

    @Autowired
    private OpActivityBiz opActivityBiz;
    @Autowired
    private OpCouponCodeBiz opCouponCodeBiz;

    /**
     * 分页搜索促销活动
     * @param opActivity 活动
     * @param currentPage 当前页
     * @param courseData 课程数据  true 搜索  false 不搜索
     * @param couponData 优惠券数据  同上
     * @param createUserData 创建用户  同上
     * @return
     */
    @RequestMapping("/queryOpActivityListPage")
    public PageInfo<OpActivity> queryOpActivityListPage(@RequestBody OpActivity opActivity,
                                                        @RequestParam(value = "currentPage",required = false,defaultValue = "1")Integer currentPage,
                                                        @RequestParam(value = "courseData",required = false,defaultValue = "false")boolean courseData,
                                                        @RequestParam(value = "couponData",required = false,defaultValue = "false")boolean couponData,
                                                        @RequestParam(value = "createUserData",required = false,defaultValue = "false")boolean createUserData,
                                                        @RequestParam(value = "subjectData",required = false,defaultValue = "false")boolean subjectData){
        Pagination page = new Pagination();
        page.setCurrentPage(currentPage);
        return opActivityBiz.queryOpActivityListPage(opActivity,page,courseData,couponData,createUserData,subjectData);
    }


    /**
     * 多条件查询促销活动
     * @param opActivity 活动
     * @param courseData 课程数据  true 搜索  false 不搜索
     * @param couponData 优惠券数据  同上
     * @param createUserData 创建用户  同上
     * @return
     */
    @RequestMapping("/queryOpActivityList")
    public List<OpActivity> queryOpActivityList(@RequestBody OpActivity opActivity,
                                                @RequestParam(value = "courseData",required = false,defaultValue = "false")boolean courseData,
                                                @RequestParam(value = "couponData",required = false,defaultValue = "false")boolean couponData,
                                                @RequestParam(value = "createUserData",required = false,defaultValue = "false")boolean createUserData,
                                                @RequestParam(value = "subjectData",required = false,defaultValue = "false")boolean subjectData){
        return opActivityBiz.queryOpActivityList(opActivity,courseData,couponData,createUserData,subjectData);
    }


    /**
     * 修改活动状态
     * @param activityIds
     * @param status
     * @return
     */
    @RequestMapping("/updateActivityStatusByIds")
    public Map<String,Object> updateActivityStatusByIds(@RequestParam("activityIds")String activityIds,
                                                        @RequestParam("status")Integer status){
        opActivityBiz.updateActivityStatusByIds(activityIds,status);
        String  message = "";
        if(status==1){
            message+="恢复成功";
        }else if (status==2){
            message+="冻结成功";
        }else if (status==3){
            message+="删除成功";
        }
        return ResultUtil.SUCCESS(message);
    }


    /**
     * 发布促销活动
     * @param activityIds
     * @param releaseStatus
     * @return
     */
    @RequestMapping("/updateActivityReleaseStatusByIds")
    public Map<String,Object> updateActivityReleaseStatusByIds(@RequestParam("activityIds")String activityIds,
                                                        @RequestParam("releaseStatus")Integer releaseStatus){
        opActivityBiz.updateActivityReleaseStatusByIds(activityIds,releaseStatus);
        return ResultUtil.SUCCESS("发布成功");
    }

    /**
     * 根据Id搜索促销活动
     * @param activityId
     * @param courseData
     * @param couponData
     * @param createUserData
     * @param subjectData
     * @return
     */
    @RequestMapping("/queryOpActivityById")
    public OpActivity queryOpActivityById(@RequestParam("activityId")BigDecimal activityId,
                                          @RequestParam(value = "courseData",required = false,defaultValue = "false")boolean courseData,
                                          @RequestParam(value = "couponData",required = false,defaultValue = "false")boolean couponData,
                                          @RequestParam(value = "createUserData",required = false,defaultValue = "false")boolean createUserData,
                                          @RequestParam(value = "subjectData",required = false,defaultValue = "false")boolean subjectData){
        return opActivityBiz.queryOpActivityById(activityId,courseData,couponData,createUserData,subjectData);
    }



    /**
     * 添加修改促销活动
     * @param opActivity
     * @return
     */
    @RequestMapping("/toAddOrUpdateActivity")
    public Map<String, Object> toAddOrUpdateActivity(@RequestBody OpActivity opActivity){
        Map<String,Object> check = checkActivityData(opActivity);
        if (ObjectUtils.isNotEmpty(check)){
            return check;
        }
        String message = "添加成功";
        if (DataUtil.idIsNotNull(opActivity.getId())){
            message="修改成功";
        }
        OpActivity _opActivity = opActivityBiz.toAddOrUpdateActivity(opActivity);
        return ResultUtil.SUCCESS(message,_opActivity);
    }

    /**
     * 查询订单可用的活动（只用于存课程商品的订单）
     * @param paramsList 限制条件
     * @param courseData 设置课程数据
     * @return List<OpActivity>
     */
    @RequestMapping("/findOrderAvailableActivityList")
    public List<OpActivity> findOrderAvailableActivityList(@RequestBody List<Map<String,String>> paramsList,@RequestParam("courseData") boolean courseData){
        return opActivityBiz.findOrderAvailableActivityList(paramsList,courseData);
    }

    /**
     * 订单查询可用的活动和优惠券数据
     * @param activityCodeCondition 查询条件
     * @return Map<String,Object>
     */
    @RequestMapping("/findOrderAvailableActivityAndCode")
    public Map<String,Object> findOrderAvailableActivityAndCode(@RequestBody ActivityCodeCondition activityCodeCondition){
        Map<String,Object> resultMap = new HashMap<>();
        if(!activityCodeCondition.isFilterCode()){//不过滤时，查询
            List<OpCouponCode> couponCodeList = opCouponCodeBiz.findOrderAvailableCodeList(activityCodeCondition.getParamsList(),activityCodeCondition.getUserId());
            resultMap.put("couponCodeList",couponCodeList);
        }
        if(!activityCodeCondition.isFilterActivity()){//不过滤时，查询
            List<OpActivity> activityList = opActivityBiz.findOrderAvailableActivityList(activityCodeCondition.getParamsList(),activityCodeCondition.isCourseData());
            resultMap.put("activityList",activityList);
        }
        return resultMap;
    }
    //====================================================================================
    /**
     * 验证活动信息数据属性
     * @param activity 活动属性对象
     * @return Map<String,Object>返回结果 ，null验证通过，不为null验证不通过
     */
    private Map<String, Object> checkActivityData(OpActivity activity) {
        if (StringUtils.isEmpty(activity.getActivityName())) {
            return ResultUtil.ERROR("请输入活动名称");
        }
        if (StringUtils.isNotEmpty(activity.getSubjectIds()) && !activity.getSubjectIds().contains(",0,")) {
            if (StringUtils.isEmpty(activity.getSubjectIds()) || activity.getSubjectIds().contains(",0,")) {
                return ResultUtil.ERROR("请选择专业、科目");
            }
        }
        if (StringUtils.isEmpty((activity.getActivityType()))) {
            return ResultUtil.ERROR("请选择活动类型");
        } else {
            if (activity.getActivityType().contains("1")) {
                if (StringUtils.isEmpty(activity.getAskAmount())) {
                    return ResultUtil.ERROR("请输入金额，可精确到小数点后一位，如：100.1");
                }
                if (!this.isDecimalAndInteger(activity.getAskAmount().toString())) {
                    return ResultUtil.ERROR("请正确输入输入金额，可精确到小数点后一位，如：100.1");
                }
                if (StringUtils.isEmpty(activity.getSubAmount())) {
                    return ResultUtil.ERROR("请输入金额，可精确到小数点后一位，如：100.1");
                }
                if (!this.isDecimalAndInteger(activity.getSubAmount().toString())) {
                    return ResultUtil.ERROR("请正确输入输入金额，可精确到小数点后一位，如：100.1");
                }
                if (activity.getSubAmount() >= activity.getAskAmount()) {
                    return ResultUtil.ERROR("消减金额不能大于或等于消费金额");
                }
            }
            if (activity.getActivityType().contains("2")) {
                if (StringUtils.isEmpty(activity.getAskAmount())) {
                    return ResultUtil.ERROR("请输入金额，可精确到小数点后一位，如：100.1");
                }
                if (!this.isDecimalAndInteger(activity.getAskAmount().toString())) {
                    return ResultUtil.ERROR("请正确输入输入金额，可精确到小数点后一位，如：100.1");
                }
                if (StringUtils.isEmpty(activity.getGiftType())) {
                    return ResultUtil.ERROR("请选择设置赠品");
                } else {
                    if (activity.getGiftType().contains("1")) {
                        if (StringUtils.isEmpty(activity.getCourseIds())) {
                            return ResultUtil.ERROR("请选择课程");
                        }
                        String[] split = StringUtils.subHeadTailString(activity.getCourseIds(),",").split(",");
                        if(split.length>3){
                            return ResultUtil.ERROR("最多赠送3门课程");
                        }
                    }
                    if (activity.getGiftType().contains("2")) {
                        if (StringUtils.isEmpty(activity.getCouponIds())) {
                            return ResultUtil.ERROR("请选择优惠券");
                        }
                        if (StringUtils.isEmpty(activity.getCouponCount())&&activity.getCouponCount()>0) {
                            return ResultUtil.ERROR("请选择赠送优惠券赠送数量");
                        }
                        if (!StringUtils.isNumber(activity.getCouponCount().toString())) {
                            return ResultUtil.ERROR("请正确添加优惠券赠送数量，格式为正整数");
                        }
                    }
                    if (activity.getGiftType().contains("3")) {
                        if (StringUtils.isEmpty(activity.getIntegral())&&activity.getIntegral()>0) {
                            return ResultUtil.ERROR("请填写赠送积分数量");
                        }
                        if (!StringUtils.isNumber(activity.getIntegral().toString())) {
                            return ResultUtil.ERROR("请正确添加积分，格式为正整数");
                        }
                    }
                }
            }
        }

        if (!StringUtils.isNotEmpty(activity.getBeginTime())) {
            return ResultUtil.ERROR("请输入活动开始时间");
        }
        if (!ObjectUtils.isNotEmpty(activity.getEndTime())) {
            return ResultUtil.ERROR("请输入活动结束时间");
        }
        if ((StringUtils.isEmpty(activity.getDepict()))) {
            return ResultUtil.ERROR("请输入活动说明");
        }
        return null;
    }
    /**
     * 判断字符串
     * @param str
     * @return
     */
    private boolean isDecimalAndInteger(String str) {
        //检查是否为空
        if (StringUtils.isEmpty(str)) {
            return false;
        }
        return Pattern.matches("^\\d+\\.?\\d?", str);
    }
}
